package com.huangdada.hfweather.service.impl;

import com.huangdada.hfweather.service.OssService;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @Description: 七牛云业务逻辑实现
 * @PROJECT_NAME: hf-weather
 * @CLASS_NAME:
 * @Author: huanglibin
 * @Date: 2020-04-02 20:58
 * @Version: 1.0
 */
@Service
public class OssServiceImpl implements OssService, InitializingBean {
    /** 上传管理 */
    @Autowired
    private UploadManager uploadManager;

    /** 实例管理 */
    @Autowired
    private BucketManager bucketManager;

    /** 认证 */
    @Autowired
    private Auth auth;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.cdn.prefix}")
    private String prefix;

    /**
     * 定义七牛云上传的相关策列
     */
    private StringMap putPolicy;

    /**
     * 获取上传凭证
     * @return
     */
    private String getUploadToken(){
        return this.auth.uploadToken(bucket,null,3600,putPolicy);
    }

    @Override
    public String uploadFile(File file, String fileName) throws QiniuException {
        Response response = this.uploadManager.put(file,fileName,getUploadToken());
        int retry = 0;
        while (response.needRetry() && retry <3){
            response = this.uploadManager.put(file,fileName,getUploadToken());
            retry++;
        }
        if (response.statusCode == 200){
            return new StringBuffer().append(prefix).append(fileName).toString();
        }
        return "上传失败！";
    }

    @Override
    public String uploadFile(InputStream inputStream, String fileName) throws QiniuException {
        Response response = this.uploadManager.put(inputStream,fileName,getUploadToken(),null,null);
        int retry = 0;
        while (response.needRetry() && retry < 3){
            response = this.uploadManager.put(inputStream,fileName,getUploadToken(),null,null);
            retry++;
        }
        System.out.println("addr==="+response.address);
        if (response.statusCode == 200){
            return new StringBuffer().append(prefix).append(fileName).toString();
        }
        return "上传失败！";
    }

    @Override
    public String delete(String key) throws QiniuException {
        Response response = bucketManager.delete(bucket, key);
        int retry = 0;
        while (response.needRetry() && retry<3){
            response = bucketManager.delete(bucket, key);
            retry++;
        }
        return response.statusCode == 200 ? "删除成功" : "删除失败！";
    }

    @Override
    public String downLoadFile(String fileName) throws UnsupportedEncodingException {
        String encodedFileName = URLEncoder.encode(fileName,"utf-8").replace("+","%20");
        String publicUrl = String.format("%s%s",prefix,encodedFileName);
        //自定义链接过期时间
        long expireInSeconds = 3600;
        String finalUrl = auth.privateDownloadUrl(publicUrl,expireInSeconds);
        return finalUrl;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.putPolicy = new StringMap();
        putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width), \"height\":${imageInfo.height}}");
    }
}
